Assert
At first glance, assertions are not exciting. They don't make your program run faster and they don't significantly reduce the code you have to write. However, when used correctly, they may do something just as important: keeping your software easily maintainable. By using assertions, you can not only find bugs faster but also transition the software from one programmer to another more easily. If you've ever picked up someone else's ColdFusion code, you can appreciate the value of this capability.
The assertion API presented is simple and concise. To make the most of it, one must not only adopt the tags, but also a methodology to go with those tags. I encourage you to try it.
Assert Methodology
To understand an assert methodology, you must first understand what an assertion is. An assertion is nothing more than a declaration by a programmer that some fact is true. For example, a programmer may assert that the value of X is greater than 10. Any fact that can be tested for its truth can be asserted. There are specific kinds of assertions, such as those that are made at the beginning of a block of code and those that are made at the end of a block. These are called pre and post conditions, respectively. In this approach, I do not distinguish between the two.
The Assert API provides a simple way of declaring an assertion by using the tag named fact. This tag is used by providing an expression to it, which is checked to see if it is true. If it is, nothing happens. If the test is false, the assertion is considered false and some action is taken.
Now that you have a way to check a single assertion, you must consider how to use this capability to write more maintainable software. The recommended assert methodology consists of two facets. The first is a set of rules to live by and the second is the enhancement of some common programming techniques with assertions. The rules are as follows:
- Only declare an assertion when you are 100% confident that it is true
- Assertions are only allowed to check variables; they are never allowed to make changes to your program
By knowing that all assertions represent true statements, you can depend on their accuracy. Because assertions cannot change a program in any way, you can safely remove or ignore them without changing the understanding of the overall program.
The rest of the methodology consists of enhancing common programming techniques with assertions. These techniques include testing, logging and commenting.
Testing
A robust piece of software depends on an exhaustive test suite. Assertions can augment the test suite by being considered tiny tests that are written directly in the code you are testing. Every time the program runs, these test cases run as well. This means the software is constantly being tested, which is quite an advantage. This is especially useful in a production environment where circumstances are being executed that you never would have imagined. By using assert statements, you can find an issue with a specific test rather than through a mysterious bug report.
Logging
Assert statements can often replace logging when you use them as a debugging mechanism. Logging for debugging purposes typically consists of outputting values from your program to be examined later. In my experience, this has often been an extremely ineffective approach to debugging software. The problem is this: The value that you log when attempting to understand a problem is typically uninteresting once the problem has been solved. The result is that you must either remove the logging statement, leave the logging statement in but make sure it never gets turned on again, or leave the statement in and simply ignore the outputted values. If the problem should ever occur again, you either are not logging the information used to fix it or else you are logging it—as well as a large volume of additional information—which makes it difficult to recognize the problem. Essentially, you either log too much information or not enough. If instead of inserting a logging statement, you insert an assert statement, then these problems will disappear. If the bug is fixed and does not return, the assert statement quietly runs but does not return an issue. If the bug does return, you will be notified through a specific assertion error instead of through the noise of a log file.
Commenting
Adding human-readable text to explain some section of code is the time-old practice of commenting. Assertions can often replace comments, especially those that make specific claims about the state of a program. While commenting is important, it suffers from a serious problem. Mainly, it can disagree with the code it is trying to explain. This puts you in a compromising position because you must either agree with the comment and disregard your understanding of the code or vice versa. By using an assertion instead of a comment, you can explain some circumstance and check that explanation every time the code is executed. Whenever you pick up code that uses assertions instead of comments, you know that the assertions are indeed true.
Installing Assert
Follow the steps below to install the Assert package:
- Shut down your ColdFusion server.
- Copy the custom tags in the tags directory to wwwroot/cf_tags/assert/, where wwwroot is the location of your web server's web root (this directory may not be under the CFusionMX directory).
- Copy the examples directory to a location under wwwroot.
- Start your CF server
- Browse to the examples directory that you installed under webroot and experiment with the included samples.
Using Assert
Two tags are part of the Assert API. The fact tag declares a fact to be true. If at any point the fact is found to be false, the assertion fails. The fail tag, if executed, causes an assertion to be raised. The fail tag is equivalent to calling the fact tag with a false value and is simply provided as a convenience. Table 1 summarizes the attributes used by the tags.
Table 1. Assert API Tags
| Name | Description | Sample Value |
expr |
The value checked in the tag. This must always be true or false. This attribute is used in the fact tag, not the fail tag. |
expr = #x + 2 GT y# |
vars |
A comma-separated list of variables shown in the assertion error message. |
vars = "x,y" |
comment |
Additional text shown in the assertion error message. |
comment = "unexpected value of x" |
Below is some extracted code that makes use of the Assert API:
<cfimport taglib="/cf_tags/assert" prefix="assert" />
<assert:fact expr = #listLen(nums) GT 0 AND n1 GT 0#
vars = "nums,n1" comment = "didn't find n1"/>
<assert:fail comment="Should never have gotten here!"/>
The first line uses the cfimport tag to make the Assert tags available. The assert:fact tag performs a test examining the length of the nums variable and checks to make sure that n1 is greater than 0. If the test fails, nums and n1 will be shown in the error message, along with the phrase "didn't find n1."
See the examples directory for more complete examples.
If the value of expr handed into the fact tag is true, the tag has no result and execution continues as normal. However, if false is handed in or if the fail tag is ever executed, an assertion failure condition occurs. When this condition happens, an assertion error report is generated, which includes such information as the page the error occurred on, the comment and requested variables, and other details.
You can handle this report in one of four ways: turn it into an exception, log it to a file, e-mail it to a user, or simply ignore it. Ignoring assertions is not recommended, but this ability is provided simply for completeness. By default, assertions are turned into exceptions. You can control this behavior by setting the application.assert.handler variable, respectively, to the value "exception," "log," "mail," or "none."
Table 2 describes the different variables that you can use to control these assertion handlers.
Table 2. Assertion Handler Variables
| Variable | Description | Sample Value |
application.assert.log.type |
Logging type to use; a type recognized by cflog |
"warning" |
application.assert.log.file |
Filename to log to; the same type of name used by cflog |
"assertErrors" |
application.assert.mail.to |
Address to send assertion failures to |
"recipient@mail.com" |
application.assert.mail.from |
"From" address in the assertion failure notices |
"assertions@mail.com" |
Implementing the Assert Framework
The Assert framework is implemented as two ColdFusion custom tags. Both custom tags call the assertionFailed function when they need to register a failed assertion. If you wish to insert additional assertion handlers or change the way a current handler is implemented, this would be the function to change.
One common goal in implementing any Assert framework is to make it as terse as possible. Assert tags should be easy to write and easy for the eye to skip over, if necessary. Therefore, I attempted to require as few arguments to the Assert tag as possible, while still providing a useful error report. ColdFusion made this goal attainable by providing such data as the CGI global variables, which allowed me to get a large amount of page information without the user providing it. I also made use of the caller scope so users could provide relevant variable names and include their value in the assertion report.
Including Assert tags in your code is an ironic exercise: You write them hoping
that they will never be used. However, this does not diminish their importance.
You only need to have your 100%-sure assertion proven false to see the value
of adopting an assertion methodology. So the next time you get the urge to
add a logging statement or a comment, consider using an Assert. The person
who reads your code after you will thank you.